package wsclients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.handler.AbstractHandler;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.codehaus.xfire.transport.http.EasySSLProtocolSocketFactory;
import org.codehaus.xfire.util.LoggingHandler;
import org.codehaus.xfire.util.dom.DOMInHandler;
import org.codehaus.xfire.util.dom.DOMOutHandler;
import org.jdom.Element;
import org.jdom.Namespace;

import com.avetti.commerce.webservices.Categories;
import com.avetti.commerce.webservices.CategoryService;

public class CategoryServiceTest {

    static {
        ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
        Protocol protocol = new Protocol("https", easy, 443);
        Protocol.registerProtocol("https", protocol);
    }

    public void test(String[] args) throws IOException {
        
        if (args.length == 0) {
            System.out.println("Usage:");
            System.out.println("\t run \t create");
            System.out.println("\t run \t delete");
            System.out.println("\t run \t findItemsId");
            return;
        }
        
        System.out.println("plealse input URL");
        String url = new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("plealse input the vendorid");
        String vid = new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("plealse input the admin name");
        String admin = new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("plealse input the password");
        String pwd = new BufferedReader(new InputStreamReader(System.in)).readLine();

        Service serviceModel = new ObjectServiceFactory().create(CategoryService.class);
        CategoryService service = (CategoryService) new XFireProxyFactory().create(
                serviceModel, url);
        
        serviceModel.addInHandler(new DOMInHandler());
        serviceModel.addOutHandler(new DOMOutHandler());
        serviceModel.addFaultHandler(new DOMOutHandler());
        
        serviceModel.addInHandler(new LoggingHandler());
        serviceModel.addOutHandler(new LoggingHandler());
        serviceModel.addFaultHandler(new LoggingHandler());

        Client client = Client.getInstance(service);
        client.addOutHandler(new VendorIdHandler(vid));
        client.addOutHandler(new UserPassHandler(admin, pwd));
        
        
        	
        if (args[0].equalsIgnoreCase("create")) {

            Categories categories = new Categories();
            System.out.println("please enter category name:");
            String catname = new BufferedReader(
                    new InputStreamReader(System.in)).readLine().trim();
            System.out.println("please enter category description:");
            String catdesc = new BufferedReader(
                    new InputStreamReader(System.in)).readLine().trim();

            categories.setVendorid(vid);
            categories.setName(catname);
            categories.setDescription(catdesc);

            try {
                service.create(categories);
            } catch (XFireFault xff) {
                System.out.println(xff.getMessage());
                return;
            }catch(XFireRuntimeException xfre){
                System.out.println(xfre.getMessage());
                return;
            }
            System.out.println("category add successfully.");
        }

        if (args[0].equalsIgnoreCase("findItemsId")) {

            Categories categories = new Categories();
            System.out.println("please enter category id:");
            String cid = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
            
            
            try {
                categories.setVendorid(vid);
                categories.setCategoryid(Long.parseLong(cid));
                List<Long> list=service.findItemsId(categories);
                
                System.out.println("found ("+list.size()+") Item identifiers:");
                for(Long id : list){
                    System.out.println(id);
                }
            } catch (NumberFormatException nfe) {
                System.out.println("please enter number for category id!");
            } catch(XFireRuntimeException xfre){
                System.out.println(xfre.getMessage());
            }
        }
        
        if (args[0].equalsIgnoreCase("delete")) {

            Categories categories = new Categories();
            System.out.println("please enter category id:");
            String cid = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
            
            
            try {
                categories.setVendorid(vid);
                categories.setCategoryid(Long.parseLong(cid));
                service.delete(categories);
            } catch(XFireRuntimeException xfre){
                System.out.println(xfre.getMessage());
                return;
            }
            System.out.println("category delete successfully.");
        }
    }

    private class VendorIdHandler extends AbstractHandler {
        private String vendorId;

        VendorIdHandler(String vendorId) {
            super();
            this.vendorId = vendorId;
        }

        public String getVendorId() {
            return vendorId;
        }

        public void setVendorId(String vendorId) {
            this.vendorId = vendorId;
        }

        public void invoke(MessageContext context) throws Exception {
            final Namespace ns = Namespace.getNamespace("urn:commerce:vendor");
            Element header = context.getOutMessage().getHeader();

            if (header == null) {
                header = new Element("header");
                context.getOutMessage().setHeader(header);
            }

            Element vendor = new Element("VendorToken", ns);
            Element vendor_el = new Element("VendorId", ns);
            vendor_el.addContent(vendorId);
            vendor.addContent(vendor_el);
            header.addContent(vendor);
        }
    }

    private class UserPassHandler extends AbstractHandler {
        private String user;
        private String pass;

        UserPassHandler(String user, String pass) {
            super();
            this.user = user;
            this.pass = pass;
        }

        public void invoke(MessageContext context) throws Exception {
            final Namespace ns = Namespace.getNamespace("urn:commerce:authentication");
            Element header = context.getOutMessage().getHeader();

            if (header == null) {
                header = new Element("header");
                context.getOutMessage().setHeader(header);
            }

            Element root = new Element("AuthenticationToken", ns);
            Element username_el = new Element("Username", ns);
            Element password_el = new Element("Password", ns);

            username_el.addContent(user);
            password_el.addContent(pass);
            root.addContent(username_el);
            root.addContent(password_el);

            header.addContent(root);
        }
    }

    public static void main(String[] args) throws IOException {
        CategoryServiceTest cst=new CategoryServiceTest();
        cst.test(args);
    }
}
